package com.sale.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.domain.R;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.dict.utils.DictUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.redis.utils.RedisUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.RemoteCodeService;
import com.sale.system.api.RemoteReviewService;
import com.sale.system.api.RemoteStaffManagementService;
import com.sale.system.api.RemoteUserService;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.dto.SysStaffManagementDto;
import com.sale.system.api.domain.dto.SysTheDropApiDto;
import com.sale.system.api.domain.vo.SysAuditHistoryVo;
import com.sale.system.domain.PullDown;
import com.sale.system.domain.SysOrderSupplier;
import com.sale.system.domain.dto.ConverterMqDto;
import com.sale.system.domain.dto.OrderSupplierManagementMqDto;
import com.sale.system.domain.dto.SysOrderSupplierDto;
import com.sale.system.domain.dto.SysOrderSupplierManagementMqDto;
import com.sale.system.domain.vo.OrderReviewVo;
import com.sale.system.domain.vo.SysOrderSupplierVo;
import com.sale.system.export.SysOrderSupplierManagementExport;
import com.sale.system.export.SysOrderSupplierManagementImportExport;
import com.sale.system.mapper.SysOrderSupplierMapper;
import com.sale.system.service.ISysExamineService;
import com.sale.system.service.SysOrderSupplierService;
import com.sale.system.util.SysVariousMqUtil;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 供应商实现层
 */
@RequiredArgsConstructor
@Service
public class SysOrderSupplierServiceImpl implements SysOrderSupplierService {


    private final SysOrderSupplierMapper sysOrderSupplierMapper;


    //private final PurchaseOrderMapper purchaseOrderMapper;

    @DubboReference
    RemoteStaffManagementService remoteStaffManagementService;

    @DubboReference
    private final RemoteCodeService remoteCodeService;

    @DubboReference
    private final RemoteReviewService remoteReviewService;

    @DubboReference
    RemoteUserService remoteUserService;

    @Resource
    ISysExamineService sysExamineService;

    /**
     * 供应商分页查询
     *
     * @param sysOrderSupplierVo
     * @return
     */
    @Override
    public TableDataInfo<SysOrderSupplierDto> getList(SysOrderSupplierVo sysOrderSupplierVo, PageQuery pageQuery) {

        //状态
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "order_supplier_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //供应商等级
        List<SysDictData> levelArray = CacheUtils.get(CacheNames.SYS_DICT, "order_supplier_level");
        Map<String, String> levelMap = levelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //用户列表
        List<SysTheDropApiDto> sysTheDropApiDtos = remoteUserService.userThe();
        Map<String, String> map = sysTheDropApiDtos.stream()
            .collect(Collectors.toMap(SysTheDropApiDto::getValue, SysTheDropApiDto::getLabel));

        Page<SysOrderSupplierDto> allList = sysOrderSupplierMapper.getAllList(pageQuery.build(), sysOrderSupplierVo);
        List<SysOrderSupplierDto> records = allList.getRecords();
        for (SysOrderSupplierDto entity : records) {
            if (entity.getAscriptionBy() != null) {
                //归属人
                String staffId = entity.getAscriptionBy();
                entity.setAscriptionByDict(map.get(staffId));
            }
            //状态
            entity.setAuditStatusDict(statusMap.get(entity.getAuditStatus()));
            //客户等级
            entity.setSupplierLevelDict(levelMap.get(entity.getSupplierLevel()));
        }
        return TableDataInfo.build(allList);
    }

    /**
     * 新增供应商
     *
     * @param sysOrderSupplierVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addSupplier(SysOrderSupplierVo sysOrderSupplierVo) throws Exception {
        //判断简称是否存在
        SysOrderSupplier SysOrderSupplierOne = sysOrderSupplierMapper.selectOne(new QueryWrapper<SysOrderSupplier>().lambda().eq(SysOrderSupplier::getSupplierAbbreviation, sysOrderSupplierVo.getSupplierAbbreviation()));
        if (SysOrderSupplierOne != null) {
            throw new GlobalException("该供应商简称已经存在");
        }

        SysOrderSupplier sysOrderSupplier = new SysOrderSupplier();
        sysOrderSupplier.setDeptId(LoginHelper.getDeptId());
        sysOrderSupplier.setSupplierName(sysOrderSupplierVo.getSupplierName());
        sysOrderSupplier.setSupplierAbbreviation(sysOrderSupplierVo.getSupplierAbbreviation());
        String authorityCoding = remoteCodeService.authorityCoding("order:purchase:supplier:list");
        if (authorityCoding == null) {
            throw new GlobalException("未进行单据配置,单据编码生成失败");
        }
        sysOrderSupplier.setSupplierNum(authorityCoding);
        sysOrderSupplier.setSupplierLevel(sysOrderSupplierVo.getSupplierLevel());
        sysOrderSupplier.setCreateBy(LoginHelper.getUsername());
        sysOrderSupplier.setContactsBy(sysOrderSupplierVo.getContactsBy());
        sysOrderSupplier.setContactsInformation(sysOrderSupplierVo.getContactsInformation());
        sysOrderSupplier.setSupplierAddress(sysOrderSupplierVo.getSupplierAddress());
        sysOrderSupplier.setInvoicingInformation(sysOrderSupplierVo.getInvoicingInformation());
        sysOrderSupplier.setBusinessLicense(sysOrderSupplierVo.getBusinessLicense());
        sysOrderSupplier.setAuditStatus(2);
        sysOrderSupplier.setCreateTime(new Date());
        sysOrderSupplier.setRemark(sysOrderSupplierVo.getRemark());
        sysOrderSupplier.setSupplierCategoryCode(sysOrderSupplierVo.getSupplierCategoryName());
        sysOrderSupplier.setRatepayerNumber(sysOrderSupplierVo.getRatepayerNumber());
        sysOrderSupplier.setContactsPhone(sysOrderSupplierVo.getContactsPhone());
        sysOrderSupplier.setBankDeposit(sysOrderSupplierVo.getBankDeposit());
        sysOrderSupplier.setOpenAccount(sysOrderSupplierVo.getOpenAccount());
        if (!("".equals(sysOrderSupplierVo.getAscriptionBy()))) {
            sysOrderSupplier.setAscriptionBy(Long.parseLong(sysOrderSupplierVo.getAscriptionBy()));
        }
        int insert = sysOrderSupplierMapper.insert(sysOrderSupplier);
        //mq发送消息
        SysOrderSupplierManagementMqDto orderSupplierManagementMqDto = new SysOrderSupplierManagementMqDto();
        BeanUtils.copyProperties(sysOrderSupplier, orderSupplierManagementMqDto);
        //租户id
        String userIdStr = LoginHelper.getUserIdStr();
        String tenantId = RedisUtils.getCacheObject(userIdStr);
        orderSupplierManagementMqDto.setTenantId(Long.parseLong(tenantId));
        orderSupplierManagementMqDto.setId(sysOrderSupplier.getId());
        SysVariousMqUtil.orderSupplierManagementMqSend(orderSupplierManagementMqDto);
        return insert > 0;
    }

    /**
     * 冻结供应商
     */
    @Override
    public boolean frozenSupplier(Long id) {
        //获取供应商信息
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(id);
        if (sysOrderSupplier.getAuditStatus() == 1) {
            sysOrderSupplier.setAuditStatus(4);
            return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
        } else {
            throw new GlobalException("只能冻结启用的供应商");
        }

    }

    /**
     * 解冻供应商
     *
     * @param id
     * @return
     */
    @Override
    public boolean thawSupplier(Long id) {
        //获取供应商信息
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(id);
        if (sysOrderSupplier.getAuditStatus() == 4) {
            sysOrderSupplier.setAuditStatus(1);
            return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
        } else {
            throw new GlobalException("只能解冻已冻结的供应商");
        }

    }

    /**
     * 撤销审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean revokeApproval(Long id) {
        //获取供应商信息
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(id);
        if (sysOrderSupplier.getAuditStatus() == 3) {
            sysOrderSupplier.setAuditStatus(2);

//            //删除审核代办消息提醒
//            feignService.deleteDoc(SysOrderSupplier.getSupplierNum(),"供应商管理");

            return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
        } else {
            throw new GlobalException("只能撤销待审核的数据");
        }

    }

    /**
     * 获取导出数据列表
     *
     * @param sysOrderSupplierVo
     * @return
     */
    @Override
    public List<SysOrderSupplierManagementExport> getInfoExport(SysOrderSupplierVo sysOrderSupplierVo) {
        List<SysOrderSupplierManagementExport> exportList;
//        //获取供应商状态缓存字典数据
//        List<SysDictData> statusArray = DictUtils.getDictCache("order_supplier_status");
//        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//
//        //获取供应商等级缓存字典数据
//        List<SysDictData> levelArray = DictUtils.getDictCache("order_supplier_level");
//        Map<String, String> levelMap = levelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        if (sysOrderSupplierVo.getIdStr() == null) {
            exportList = sysOrderSupplierMapper.getExportList(sysOrderSupplierVo);
        } else {
            List<String> idList = Arrays.asList(sysOrderSupplierVo.getIdStr().split(","));
            exportList = sysOrderSupplierMapper.getDataByIdStr(idList);
        }
        for (SysOrderSupplierManagementExport entity : exportList) {
//            //状态
//            entity.setAuditStatus(statusMap.get(entity.getAuditStatus()));
//            //等级
//            entity.setSupplierLevel(levelMap.get(entity.getSupplierLevel()));
            if (entity.getAscriptionBy() != null) {
                //归属人
                String ascriptionBy = entity.getAscriptionBy();
//                entity.setAscriptionBy(feignService.getUserName(Long.valueOf(ascriptionBy)));
            }
        }
        return exportList;
    }

    /**
     * 导入
     *
     * @param coCustomer
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importMouldData(List<SysOrderSupplierManagementImportExport> coCustomer) {
        if (coCustomer.size() == 0) {
            throw new GlobalException("导入供应商信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //获取供应商等级缓存字典数据
        List<SysDictData> levelArray = DictUtils.getDictCache("order_supplier_level");
        Map<String, String> levelMap = levelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (SysOrderSupplierManagementImportExport mouldModelExport : coCustomer) {
            SysOrderSupplier sysOrderSupplier = new SysOrderSupplier();
            try {
                if (mouldModelExport.getSupplierName() == null || mouldModelExport.getSupplierAbbreviation() == null || mouldModelExport.getSupplierLevel() == null) {
                    throw new GlobalException("存在必填字段为空，请核实");
                }
                // 赋值
                sysOrderSupplier.setSupplierName(mouldModelExport.getSupplierName());
                sysOrderSupplier.setContactsBy(mouldModelExport.getContactsBy());
                sysOrderSupplier.setContactsInformation(mouldModelExport.getContactsInformation());
                sysOrderSupplier.setSupplierAddress(mouldModelExport.getSupplierAddress());
                //判断简称是否唯一
                SysOrderSupplier sysOrderSupplierOne = sysOrderSupplierMapper.selectOne(new QueryWrapper<SysOrderSupplier>().lambda().eq(SysOrderSupplier::getSupplierAbbreviation, mouldModelExport.getSupplierAbbreviation()));
                if (sysOrderSupplierOne != null) {
                    throw new GlobalException("该供应商简称已经存在");
                }
                sysOrderSupplier.setSupplierAbbreviation(mouldModelExport.getSupplierAbbreviation());
                //供应商等级
                for (Map.Entry<String, String> entry : levelMap.entrySet()) {
                    if (entry.getValue().equals(mouldModelExport.getSupplierLevel())) {
                        sysOrderSupplier.setSupplierLevel(Integer.parseInt(entry.getKey()));
                        break;
                    }
                }
                sysOrderSupplier.setCreateBy(LoginHelper.getUsername());
                sysOrderSupplier.setAuditStatus(1);
                //获取供应商编码
                String authorityCoding = remoteCodeService.authorityCoding("order:supplier:list");
                if (authorityCoding == null) {
                    throw new GlobalException("未进行单据配置,单据编码生成失败");
                }
                sysOrderSupplier.setSupplierNum(authorityCoding);
                sysOrderSupplier.setCreateTime(new Date());
                //判断归属人是否存在

                String userName = mouldModelExport.getAscriptionBy();
//                if (userName != null) {
//                    AjaxResult byUserName = feignService.getByUserName(userName);
//                    if (byUserName == null) {
//                        throw new GlobalException("未获取到相关归属人");
//                    }
//                    SysUser data = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);
//                    SysOrderSupplier.setAscriptionBy(data.getUserId());
//                }
                sysOrderSupplier.setDeptId(LoginHelper.getDeptId());
                sysOrderSupplierMapper.insert(sysOrderSupplier);

//                //mq发送消息
//                SysOrderSupplierMqDto SysOrderSupplierMqDto = new SysOrderSupplierMqDto();
//                BeanUtils.copyProperties(SysOrderSupplier, SysOrderSupplierMqDto);
//                VariousMqUtil.SysOrderSupplierMqSend(SysOrderSupplierMqDto);

                successNum++;
                successMsg.append(successNum + "、供应商信息 " + mouldModelExport.getSupplierName() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、供应商 " + mouldModelExport.getSupplierName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }

    /**
     * 删除供应商
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSupplierByIds(String ids) throws Exception {
        List<SysOrderSupplier> SysOrderSupplierList = new ArrayList<>();
        if (ids != null) {
            List<String> stringIds = Arrays.asList(ids.split(","));
            //获取供应商列表
            List<SysOrderSupplier> sysOrderSuppliers = sysOrderSupplierMapper.selectBatchIds(stringIds);

            for (SysOrderSupplier entity : sysOrderSuppliers) {
                if (entity.getAuditStatus() != 2 && entity.getAuditStatus() != 6) {
                    throw new GlobalException("只能删除待提交、未通过的数据");
                }
//                List<PurchaseOrder> purchaseOrders = purchaseOrderMapper.selectList(new QueryWrapper<PurchaseOrder>().lambda().eq(PurchaseOrder::getSupplierId, entity.getId()));
                //如果没有关联数据，并且状态为已冻结，就放入删除列表
//                boolean delData = 6 == entity.getAuditStatus() && purchaseOrders.size() == 0;
//                if (delData || entity.getAuditStatus() == 2 || entity.getAuditStatus() == 5) {
                SysOrderSupplierList.add(entity);

//                    feignService.deleteDoc(entity.getSupplierNum(),"供应商管理");

//                }
            }

//            if (SysOrderSupplierList.size() > 0) {
//                StringBuilder stringBuilder = new StringBuilder();
//                for (SysOrderSupplier entity : SysOrderSupplierList) {
//                    stringBuilder.append(entity.getSupplierNum()).append(",");
//                }
//                StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
//                //mq同步删除加工商
//                SysOrderSupplierMqDto SysOrderSupplierMqDto = new SysOrderSupplierMqDto();
//                SysOrderSupplierMqDto.setSupplierDeleteMark(12);
//                SysOrderSupplierMqDto.setSupplierNum(stringBuilder1.toString());
//                VariousMqUtil.SysOrderSupplierMqSendDelete(SysOrderSupplierMqDto);
        } else {
            throw new GlobalException("请至少勾选一条数据");
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (SysOrderSupplier entity : SysOrderSupplierList) {
            stringBuilder.append(entity.getId()).append(",");
        }
        StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        //mq同步删除加工商
        SysOrderSupplierManagementMqDto SysOrderSupplierMqDto = new SysOrderSupplierManagementMqDto();
        SysOrderSupplierMqDto.setIdStr(stringBuilder1.toString());
        SysVariousMqUtil.orderSupplierManagementMqSendDelete(SysOrderSupplierMqDto);
        return sysOrderSupplierMapper.deleteBatchIds(SysOrderSupplierList) > 0;

    }

    /**
     * 查看供应商信息
     *
     * @param id
     * @return
     */
    @Override
    public SysOrderSupplierDto getSupplierById(Long id) {
        SysOrderSupplierDto supplierById = sysOrderSupplierMapper.getSupplierById(id);
        //用户列表
        List<SysTheDropApiDto> sysTheDropApiDtos = remoteUserService.userThe();
        Map<String, String> map = sysTheDropApiDtos.stream()
            .collect(Collectors.toMap(SysTheDropApiDto::getValue, SysTheDropApiDto::getLabel));

        if (supplierById.getAscriptionBy() != null) {
            //归属人
            String staffId = supplierById.getAscriptionBy();
            supplierById.setAscriptionByDict(map.get(staffId));
        }
//        //获取供应商所属机构缓存字典数据
//        List<SysDictData> organizationArray = DictUtils.getDictCache("order_affiliated_organization");
//        Map<String, String> organizationMap = organizationArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//        SysOrderSupplierDto.setAffiliatedOrganizationDict(organizationMap.get(String.valueOf(SysOrderSupplier.getAffiliatedOrganization())));
//        SysOrderSupplierDto.setAffiliatedOrganization(String.valueOf(SysOrderSupplier.getAffiliatedOrganization()));
//        //获取供应商等级缓存字典数据
//        List<SysDictData> levelArray = DictUtils.getDictCache("order_supplier_level");
//        Map<String, String> levelMap = levelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//        SysOrderSupplierDto.setSupplierLevelDict(levelMap.get(String.valueOf(SysOrderSupplier.getSupplierLevel())));
//        SysOrderSupplierDto.setSupplierLevel(String.valueOf(SysOrderSupplier.getSupplierLevel()));
//        //归属人
//        Long userId = SysOrderSupplier.getAscriptionBy();
//        String userName = feignService.getUserName(userId);
//        SysOrderSupplierDto.setAscriptionBy(String.valueOf(userId));
//        SysOrderSupplierDto.setAscriptionByDict(userName);
        return supplierById;
    }


    /**
     * 根据供应商编码查询供应商详情信息
     *
     * @param code
     * @return
     */
    @Override
    public SysOrderSupplierDto getSupplierByNum(String code) {
        SysOrderSupplierDto supplierByNum = sysOrderSupplierMapper.selectByCode(code);
//        if (supplierByNum.getAscriptionBy() != null) {
//            //归属人
//            Long staffId = Long.valueOf(supplierByNum.getAscriptionBy());
//            R<SysStaffManagementDto> info = remoteStaffManagementService.getInfo(staffId);
//            if (info.getData() != null) {
//                supplierByNum.setAscriptionByDict(info.getData().getStaffName());
//            }
//        }
//
        return supplierByNum;
    }


    /**
     * 提交审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean reivewSubmit(Long id) {
        SysOrderSupplier SysOrderSupplier = sysOrderSupplierMapper.selectById(id);
        if (SysOrderSupplier.getAuditStatus() == 2) {
            SysOrderSupplier.setAuditStatus(3);

//            //新增审核代办
//            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
//
//            sysWorkbenchAuditAgentVo.setReceiptName("供应商管理");
//            sysWorkbenchAuditAgentVo.setDocConfig("order:purchase:supplier:examine");
//            sysWorkbenchAuditAgentVo.setReceiptNumber(SysOrderSupplier.getSupplierNum());//供应商编号
//            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
//            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");
//
//            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

            return sysOrderSupplierMapper.updateById(SysOrderSupplier) > 0;
        } else {
            throw new GlobalException("只能操作待提交的数据");
        }

    }

    /**
     * 修改供应商
     *
     * @param sysOrderSupplierVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSupplierById(SysOrderSupplierVo sysOrderSupplierVo) throws Exception {
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(sysOrderSupplierVo.getId());
        BeanUtils.copyProperties(sysOrderSupplierVo, sysOrderSupplier);
        sysOrderSupplier.setAscriptionBy(Long.parseLong(sysOrderSupplierVo.getAscriptionBy()));
        if (sysOrderSupplier.getAuditStatus() == 6) {
            //调用审核
            SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
            String perms = "informateManage:supplier:examine";
            String auditDoc = sysOrderSupplier.getSupplierNum();
            sysAuditHistoryVo.setAuditDoc(auditDoc);
            sysAuditHistoryVo.setPerms(perms);
            int i = sysExamineService.updateHistoryAppConfigEdit(sysAuditHistoryVo);
            if (i > 0) {
                sysOrderSupplier.setAuditStatus(2);
                //mq发送消息
                SysOrderSupplierManagementMqDto sysOrderSupplierManagementMqDto = new SysOrderSupplierManagementMqDto();
                BeanUtils.copyProperties(sysOrderSupplier, sysOrderSupplierManagementMqDto);
                SysVariousMqUtil.orderSupplierManagementMqSend(sysOrderSupplierManagementMqDto);
                //修改审核代办状态为已处理
//                    feignService.updateStatus(3, converterManagement.getConverterNum(), "加工商管理");
                return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
            } else {
                return false;
            }
        }
        return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
    }

    /**
     * 供应商审核
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    public boolean supplierReview(OrderReviewVo orderReviewVo) throws Exception {

        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(orderReviewVo.getId());
        if (sysOrderSupplier.getAuditStatus() == 5 || sysOrderSupplier.getAuditStatus() == 3) {
            String perms = "informateManage:supplier:examine";
            //获取菜单id
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = sysOrderSupplier.getSupplierNum();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = LoginHelper.getUserId();
            SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
            sysAuditHistoryVo.setPerms(perms);
            sysAuditHistoryVo.setAuditType(2);
            sysAuditHistoryVo.setAuditState(isAdopt);
            sysAuditHistoryVo.setAuditRemarks(auditRemarks);
            sysAuditHistoryVo.setAuditDoc(auditDoc);
            sysAuditHistoryVo.setUserId(userId);
            int data = remoteReviewService.getSequence(sysAuditHistoryVo);
            if (data == 0) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    sysOrderSupplier.setAuditStatus(1);
//                    //修改审核代办状态为已处理
//                    feignService.updateStatus(3, auditDoc, "供应商管理");

                    return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
                } else if (data == 2) {
                    sysOrderSupplier.setAuditStatus(5);
                    return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    sysOrderSupplier.setAuditStatus(6);

//                    //新增审核代办
//                    SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
//
//                    sysWorkbenchAuditAgentVo.setReceiptName("供应商管理");
//                    sysWorkbenchAuditAgentVo.setDocConfig("order:purchase:supplier:examine");
//                    sysWorkbenchAuditAgentVo.setReceiptNumber(SysOrderSupplier.getSupplierNum());//供应商编号
//                    sysWorkbenchAuditAgentVo.setStatus(2);//待处理
//                    sysWorkbenchAuditAgentVo.setPassFlag("1");
//                    sysWorkbenchAuditAgentVo.setCreateName(SysOrderSupplier.getCreateBy());
//                    sysWorkbenchAuditAgentVo.setReceiptContent("单据审核未通过,请及时查看");
//
//                    feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

                    return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("只能对待审核和审核中的数据进行处理");
        }
    }

    /**
     * 供应商启用状态修改
     *
     * @param sysOrderSupplierVo
     * @return
     */
    @Override
    public boolean updateStatus(SysOrderSupplierVo sysOrderSupplierVo) {
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(sysOrderSupplierVo.getId());
        sysOrderSupplier.setAuditStatus(Integer.parseInt(sysOrderSupplierVo.getAuditStatus()));
        return sysOrderSupplierMapper.updateById(sysOrderSupplier) > 0;
    }

    /**
     * 获取开启的供应商
     *
     * @return
     */
    @Override
    public List<HashMap<String, String>> getOpenSupplier() {
        List<HashMap<String, String>> resultMap = new ArrayList<>();
        List<SysOrderSupplierDto> openSupplierList = sysOrderSupplierMapper.getOpenSupplierList();
        for (SysOrderSupplierDto entity : openSupplierList) {
            HashMap<String, String> map = new HashMap<>();
            map.put("label", entity.getSupplierName());
            map.put("value", entity.getSupplierNum());
            resultMap.add(map);
        }
        return resultMap;
    }

    /**
     * 获取开启的供应商(财务模块调用)
     *
     * @return
     */
    @Override
    public Map<String, String> getOpenSupplierFinance() {
        List<SysOrderSupplierDto> openSupplierList = sysOrderSupplierMapper.getOpenSupplierList();
        Map<String, String> collect = openSupplierList.stream()
            .collect(Collectors.toMap(SysOrderSupplierDto::getSupplierNum, SysOrderSupplierDto::getSupplierName));
        return collect;
    }

    /**
     * 根据编码获取供应商信息
     *
     * @param code
     * @return
     */
    @Override
    public SysOrderSupplierDto getSupplierByCode(String code) {

        return sysOrderSupplierMapper.selectByCode(code);
    }

    /**
     * 通过供应商名称获取供应商编码(财务模块使用)
     */
    @Override
    public String getCodeBySupplierName(String supplierName) {
        return sysOrderSupplierMapper.getCodeBySupplierName(supplierName);
    }

    /**
     * 供应商下拉
     */
    @Override
    public List<PullDown> supplierPullDown() {
        return sysOrderSupplierMapper.supplierPullDown();
    }

    /**
     * 更新供应商余额(财务模块使用)
     */
/*    @Override
    public boolean updateSupplierBalance(CustomerBalance customer) {
        return SysOrderSupplierMapper.updateSupplierBalance(customer);
    }*/
}
